<template>
  <div id="add">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="active_index - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品照片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab 栏区域 -->
      <el-form
        :model="add_form"
        :rules="add_form_rules"
        ref="add_form_ref"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="active_index"
          :tab-position="'left'"
          :before-leave="before_tab_leave"
          @tab-click="tab_clicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="add_form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" type="number">
              <el-input v-model="add_form.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number">
              <el-input v-model="add_form.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="add_form.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器区域 -->
              <el-cascader
                expand-trigger="hover"
                :options="cate_list"
                :props="cate_props"
                v-model="add_form.goods_cat"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in many_table_data"
              :key="item.attr_id"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in only_table_data"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品照片" name="3">
            <!-- action 图片要上传的地址 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="header_obj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="add_form.goods_introduce"></quill-editor>
            <!-- 添加按钮 -->
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="preview_visiable" width="50%">
      <img :src="preview_path" alt="" class="preview" />
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  data() {
    return {
      // 步骤条的active索引值
      active_index: "0",
      // 添加商品的表单数据对象
      add_form: {
        goods_name: "",
        goods_price: "0",
        goods_weight: "0",
        goods_number: "0",
        // 商品所处的分类数组
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品的介绍
        goods_introduce: "",
        attrs: [],
      },
      // 表单验证规则对象
      add_form_rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 指定级联选择器的配置对象
      cate_props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      // 商品分类列表
      cate_list: [],
      // 动态参数列表数据
      many_table_data: [],
      // 商品属性列表数据
      only_table_data: [],
      // 图片要上传的地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片需要上传的 headers 请求头对象
      header_obj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片的路径
      preview_path: "",
      // 控制图片预览对话框的显示与隐藏
      preview_visiable: false,
    };
  },
  created() {
    this.get_cate_list();
  },
  methods: {
    // 获取所有商品分类数据
    async get_cate_list() {
      let { data: res } = await this.axios.get("categories");
      if (res.meta.status !== 200) {
        return this.message.error("获取商品分类失败");
      }
      this.cate_list = res.data;
    },
    // 监听级联选择器发生改变时,触发这个函数
    handleChange() {
      if (this.add_form.goods_cat.length !== 3) {
        this.add_form.goods_cat = [];
      }
    },
    // 阻止页签跳转
    before_tab_leave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.add_form.goods_cat.length !== 3) {
        this.message.error("请先选择商品分类");
        return false;
      }
    },
    // tab 被选中时触发
    async tab_clicked() {
      if (this.active_index === "1") {
        let { data: res } = await this.axios.get(
          `categories/${this.cate_id}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status !== 200) {
          return this.message.error("获取参数失败");
        }
        console.log(res.data);
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        this.many_table_data = res.data;
      } else if (this.active_index === "2") {
        let { data: res } = await this.axios.get(
          `categories/${this.cate_id}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200) {
          return this.message.error("获取参数失败");
        }
        console.log(res.data);
        this.only_table_data = res.data;
      }
    },
    // 处理图片预览函数
    handlePreview(file) {
      this.preview_path = file.response.data.url;
      console.log(this.preview_path);
      this.preview_visiable = true;
    },
    // 处理移除图片的操作
    handleRemove(file) {
      // 1. 获取将要删除图片的临时路径
      let file_path = file.response.data.tmp_path;
      // 2. 从 pics 中，找到这个图片的索引值
      let i = this.add_form.pics.findIndex((x) => x.pic === file_path);
      // 3. 调用数组的 splice 对象，把图片喜喜对象从 pics 这个数组中删除
      this.add_form.pics.splice(i, 1);
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // 1. 拼接得到一个图片信息对象
      let pic_info = { pic: response.data.tmp_path };
      // 2. 将图片信息对象 push 到 pics 当中
      this.add_form.pics.push(pic_info);
    },
    // 添加文本
    add() {
      this.$refs.add_form_ref.validate(async (valid) => {
        if (!valid) {
          return this.message.error("请填写必要的表单项");
        }
        // 执行添加的业务逻辑
        let form = _.cloneDeep(this.add_form);
        form.goods_cat = form.goods_cat.join(",");
        // 处理动态参数
        this.many_table_data.forEach((item) => {
          let new_info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.add_form.attrs.push(new_info);
        });
        // 处理静态属性
        this.only_table_data.forEach((item) => {
          let new_info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.add_form.attrs.push(new_info);
        });
        form.attrs = this.add_form.attrs;
        console.log(form);
        // 发起请求添加商品
        // 商品的名称，必须是唯一的
        let { data: res } = await this.axios.post("goods", form);
        if (res.meta.status !== 201) {
          console.log(res.meta.status);
          return this.message.error("添加商品失败");
        }
        this.message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },
  },
  computed: {
    cate_id() {
      if (this.add_form.goods_cat.length === 3) {
        return this.add_form.goods_cat[2];
      }
      return null;
    },
  },
};
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.preview {
  width: 100%;
}
</style>